<template>
  <div class="page">
    <write-msg :forms="forms"
               @saveCate="saveCate"
               @deleteCate="deleteCate"
               @emitEvent="emitEvent"></write-msg>
  </div>
</template>

<script>
import { c_AddCate, c_GetCateById, c_DelCate } from "@/utils/request.js"
import { confirm, c_UpdateCate } from "@/utils/function.js"
import writeMsg from "@/component/writeMsg.vue"
export default {
  components: {
    writeMsg
  },
  data () {
    return {
      cid: -1,
      name: "",
      introduce: "",
      forms: []
    }
  },
  methods: {
    saveCate: function () {
      let userId = uni.getStorageSync('userId')
      let data = JSON.stringify({ "cid": this.cid, "userId": userId, "name": this.name, "nameIntroduce": this.introduce })
      console.log(data);
      c_AddCate(data).then(res => {
        console.log(res);
        c_UpdateCate();
        if (typeof res.data.data == "string") {
          confirm(1, "修改成功", 3, '/pages/collect/index')
        } else {
          confirm(1, "添加成功", 3, '/pages/collect/index')
        }
      }).catch(err => {
        console.log(err);
        confirm(0, "添加失败", 4)
      })
    },
    deleteCate: function () {
      let data = { "cid": this.cid }
      c_DelCate(data).then(res => {
        console.log(res);
        c_UpdateCate();
        confirm(1, "删除成功", 3, '/pages/collect/index')
      }).catch(err => {
        console.log(err);
        confirm(0, "删除失败", 2, '/pages/collect/category?tid=' + this.tid)
      })
    },
    emitEvent: function (val) {
      console.log(val);
      this.name = val[0]["value"]
      this.introduce = val[1]["value"]
    }
  },
  onLoad (option) {
    this.cid = parseInt(option.cid)
    let userId = uni.getStorageSync('userId')
    let data = { "cid": this.cid, "userId": userId }
    c_GetCateById(data).then(res => {
      console.log(res);
      if (this.cid >= 0) {
        let list = res.data.data
        this.name = list.Name
        this.introduce = list.NameIntroduce
        this.forms.push({ "type": 5, "title": "删除", "change": "deleteCate", "class": "bg-gradual-red" })
      }

      this.forms.unshift({ "type": 1, "title": "新区", "placeholder": "分区名", "value": this.name },
        { "type": 2, "title": "介绍", "placeholder": "分区的简单说明", "value": this.introduce },
        { "type": 5, "title": "保存", "change": "saveCate", "class": "bg-blue" }
      )

    }).catch(err => {
      console.log(err);
    })

  }
}
</script>

<style lang="scss" scoped>
.add-form {
  .cu-form-group .title {
    min-width: calc(4em + 15px);
  }
  // textarea {
  //   display: flex;
  //   align-items: center;
  //   transform: translateY(-11px);
  // }
  button {
    width: 100%;
    height: 40px;
    font-size: 17px;
    margin-top: 10px;
  }
}
</style>